<?php

namespace App\Service\VendorClient\Shopjackyunblp;

use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

/**
 * @author hj
 * 吉客云供应商订单
 * 菠萝派-保税
 */
class ShopjackyunblpApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shopjackyunblp';

    //配置文件
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     */
    public function createOrder($param = []) {
        if (empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo'])) {
            return Normal::returnCode(Normal::FAIL, "except param supplierOrder or orderGoods or order or binfo");
        }
        $orderInfo = $param['supplierOrder'];
        $goodsList = $param['orderGoods'];
        $order     = $param['order'];
        $binfo     = $param['binfo'];
        $order_sn  = $orderInfo['supplier_dsn'];
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //电商平台信息
        $enterpriseNum  = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum  = $order['enterpriseNum'] ?? $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ?? $enterpriseName;
        //支付公司信息
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $payCommanyName = $apply_extends['payCommanyName'] ?? '';
        $payCommanyCode = $order['payCommanyCode'] ?? $payCommanyCode;
        $payCommanyName = $order['payCommanyName'] ?? $payCommanyName;
        //判断支付方式是否存在
        $payWayInfo = ServiceConfig::instance()->getConfigByEventsValue(self::SUPPLIER_CODE, ServiceConfig::TYPE_PAY, $payCommanyCode);
        // if (empty($payWayInfo)) {
        //     return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$payCommanyCode}】未映射，请联系管理员处理");
        // }
        //获取下单商品信息
        $palceOrderGoods    = [];
        $totalGoodsMoney    = '0.00';
        $goodsTotalMoney    = '0.00';
        $goodsTotalMoneyNot = '0.00';
        $wayTaxFee          = '0.00';
        $goodsType         = reset($goodsList)['goods_type'];//商品类型（0-一般贸易，1-保税商品，2-海外直邮, 3海外购）
        foreach ($goodsList as $key => $item) {
            $tax_rate         = bcadd('1', (string)$item['tax_rate'], 4);
            $goods_type       = $item['goods_type'];
            // $price            = $item['price'];
            $price            = $goods_type == 1 ? $item['price'] : $item['costprice'];//百大项目price要用供货价
            $spec_num         = $item['spec_num'];
            $quantity         = $item['quantity'];
            $supplier_skucode = $item['supplier_skucode'];
            //实际购买数量(下单数量 X 起售数量)
            $buyAcount = $spec_num * $quantity;
            // if ($key == 0) {
            //     $singleDeliveryMoney = bcdiv((string)$deliver_money, (string)$quantity, 3);
            //     $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney, (string)100, 1);
            //     $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100, 2);
            //     $price               = bcadd((string)$price, (string)$singleDeliveryMoney, 2);
            // }
            //不含税价格
            $singleGoodsPrice = bcdiv((string)$price, (string)$tax_rate, 3);
            $singleGoodsPrice = bcmul((string)$singleGoodsPrice, (string)100, 1);
            $singleGoodsPrice = bcdiv((string)ceil($singleGoodsPrice), (string)100, 2);
            //商品不含税总价
            $goodsTotalPrice = bcmul((string)$singleGoodsPrice, (string)$quantity, 2);
            //含税总价
            $goodsTotalPriceTax = bcmul((string)$price, (string)$quantity, 2);
            //税费
            $tax    = bcsub((string)$price, (string)$singleGoodsPrice, 2);
            $taxAll = bcmul((string)$tax, (string)$quantity, 2);

            //判断是不是保税订单
            $taxAll = $goods_type == 1 ? $taxAll : 0;
            //不含税总金额
            $goodsTotalMoneyNot = bcadd((string)$goodsTotalMoneyNot, (string)$goodsTotalPrice, 2);
            //含税总金额
            $goodsTotalMoney = bcadd((string)$goodsTotalMoney, (string)$goodsTotalPriceTax, 2);
            //总税费
            $wayTaxFee = bcadd((string)$wayTaxFee, (string)$taxAll, 2);
            //下单商品组
            $goodsInfo         = [
                'ProductId'      => $item['supplier_skucode'],//平台商品ID或SKUID(SKUID优先)
                // 'tradegoodsno'   => $item['skucode'],//外部商家编码或外部SKU编码
                'tradegoodsno'   => $item['supplier_skucode'],//外部商家编码或外部SKU编码
                'tradegoodsname' => $item['goods_name'],//商品交易名称
                // 'platgoodsid' => $item['goods_name'],//平台商品ID（用于吉客云对接）
                // 'platskuid' => $item['goods_name'],//平台规格ID（用于吉客云对接）
                // 'OutItemID' => $item['skucode'],//外部商家编码（用于吉客云对接
                // 'OutSkuID' => $item['skucode'],//外部规格编码（用于吉客云对接）
                'goodscount'     => (int)$quantity,//商品数量
                'price'          => $price,//单价
                'discountmoney'  => '0.00',//子订单优惠金额
                'refundStatus'   => 'JH_07',//退款状态(没有退款=JH_07，买家已经申请退款等待卖家同意=JH_01，卖家已经同意退款等待买家退货=JH_02，买家已经退货等待卖家确认收货=JH_03，卖家拒绝退款=JH_04，退款关闭=JH_05，退款成功=JH_06，其他=JH_99)
                'Status'         => 'JH_02',//子订单交易状态(其他=JH_99，等待买家付款=JH_01，等待卖家发货=JH_02，等待买家确认收货=JH_03，交易成功=JH_04，交易关闭=JH_05)
            ];
            $palceOrderGoods[] = $goodsInfo;
        }
        $totalMoney    = bcadd((string)$goodsTotalMoney, (string)$deliver_money, 2);
        //用户实际支付金额
        $real_total_money = $orderInfo['real_total_money'];
        //订单优惠金额
        $discount_money = bcsub((string)$totalMoney, (string)$real_total_money, 2);
        $requestParam = [
            'orders' => [
                [
                    'PlatOrderNo'      => $order_sn,//订单号
                    'tradeStatus'      => 'JH_02',//等待卖家发货=JH_02
                    'tradetime'        => $order_time,//交易时间(格式:yyyy-MM-dd HH:mm:ss)
                    'payorderno'       => $order['paySerial'] ?? $apply_extends['paySerial'],//支付单号
                    'province'         => $orderInfo['province'],//省
                    'city'             => $orderInfo['city'],//市
                    'area'             => $orderInfo['district'],//区
                    'address'          => $orderInfo['receive_address'],//具体地址
                    'phone'            => $orderInfo['recveive_phone'],//电话
                    'mobile'           => $orderInfo['recveive_phone'],//手机
                    'postfee'          => $deliver_money,//邮资
                    'goodsfee'         => $goodsTotalMoneyNot,//货款金额 不含税
                    // 'totalmoney'       => $orderInfo['real_total_money'],//合计应收（针对卖家）
                    // 'totalmoney'       => $goodsType == 1 ? $orderInfo['real_total_money'] : $totalMoney,//合计应收（针对卖家）
                    //针对百大修改
                    'totalmoney'       => $totalMoney,//合计应收（针对卖家）
                    // 'favourablemoney'  => $discount_money > 0 ? $discount_money : '0.00',//订单总优惠金额
                    //针对百大修改
                    'favourablemoney'  => '0.00',//订单总优惠金额
                    'platdiscountmoney'=> $discount_money > 0 ? $discount_money : '0.00',//订单总优惠金额
                    'taxamount'        => $wayTaxFee,//订单税费总额
                    'paytime'          => $pay_time,//支付时间(格式:yyyy-MM-dd HH:mm:ss)
                    'cardtype'         => 'JH_01',//证件类型(身份证=JH_01
                    'idcard'           => $orderInfo['buyer_idcard'],//证证件号码
                    'idcardtruename'   => $orderInfo['buyer_realname'],//证件真实姓名
                    'receivername'     => $orderInfo['receive_name'],//收货人姓名
                    'nick'             => $orderInfo['buyer_realname'],//买家昵称
                    'payID'            => $payCommanyCode,//支付公司海关备案号
                    'payName'          => $payCommanyName,//支付公司海关备案名称
                    'businessPlatcode' => $enterpriseNum,//电商平台海关备案编码
                    'businessPlatName' => $enterpriseName,//电商平台海关备案名称
                    'paytype'          => $payWayInfo ?: 'JH_Other',//付款方式
                    'goodinfos'        => $palceOrderGoods
                ]
            ]
        ];
        $data         = [
            'method' => 'createOrder',
            'data'   => json_encode($requestParam, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ];
        return $this->execute($data);
    }

    /**
     * 获取取消订单
     */
    public function cancelOrder($params = []) {
        $queryParam = [
            'uerName'        => $this->config['uerName'],//管家会员名 / 吉客号
            'messageType'    => 'Poly_Refund_Created',//推送的消息类型
            'targetType'     => 'Poly_JACKYUNOPEN',//推送方枚举
            'messageContent' => [
                'tid'           => $params['supplierOrder']['supplier_dsn'],//单号
                'refund_status' => 'JH_01',//买家已经申请退款等待卖家同意  平台退款状态
                'refundtype'    => 'JH_01',//买家已经申请退款等待卖家同意
            ],
        ];
        $data       = [
            'method' => 'cancelOrder',
            'data'   => json_encode($queryParam, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ];
        return $this->execute($data);
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress($params = []) {
        return Normal::returnCode(Normal::SUC, "获取成功");
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function sign($data) {
        ksort($data);
        $strA = '';
        foreach ($data as $k => $v) {
            $strA .= "{$k}{$v}";
        }
        $strB = $this->config['appSecret'] . $strA . $this->config['appSecret'];
        return md5(strtolower($strB));
    }

    /**
     * CURL请求
     * @param $params
     * @return array
     */
    public function execute($param = []) {
        $method = $param['method'];
        $data   = $param['data'];
        if (!isset($this->config[$method])) {
            return Normal::returnCode(Normal::FAIL, "请求路由未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        $url = $this->config[$method];
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        $pushData         = [
            'appkey'    => $this->config['appkey'],
            'token'     => $this->config['token'],
            'timestamp' => date('Y-m-d H:i:s'),
            'data'      => $param['data'],
        ];
        $pushData['sign'] = $this->sign($pushData);
        $parameter        = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'x-www-form-urlencoded',
                'header' => [],
            ],
        ];
        $resTask          = TaskWorker::instance()->addTask($parameter);
        $resTask          = current($resTask);
        $result           = @json_decode($resTask['response']['result'], true);
        if (isset($result['code']) && $result['code'] === '10000') {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        } else {
            $msg    = $result['msg'] ?? '请求失败';
            $subMsg = $result['submessage'] ?? '';
            return Normal::returnCode(Normal::FAIL, $msg . $subMsg);
        }
    }


}